package com.aote.entity.action;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Element;

import com.aote.component.format.FormatFactory;
import com.aote.expression.ExpressionGenerator;
import com.aote.mvc.event.Action;
import com.browsesoft.ExtendElement;
import com.browsesoft.baseadapter.HTMLLazyEntityModel;
import com.browsesoft.htmlcomponent.TemplateManager;

/**
 * 根据给定模板创建实体，要创建的实体的属性可以从当前录入的部分传过去。 其效果与带值处理效果类似。
 */
public class CreateEntityAction extends Action {
	public void performAction(Element config, HttpServletRequest request,
			Map attrs) {
		try {
			// 获得表单根元素
			String formName = config.getAttribute("form");
			Element root = TemplateManager.getInstance().getTemplateByName(
					formName).getDocument().getDocumentElement();
			Element form = (Element) root.getElementsByTagName("form").item(0);
			// 产生实体
			HTMLLazyEntityModel entity = new HTMLLazyEntityModel();
			// 从源获得属性
			Map map = new HashMap();
			map.put("entitytype", form.getAttribute("entitytype"));
			Iterator iter = ExtendElement.findElementsOfAttr(form, "fieldtype")
					.iterator();
			while (iter.hasNext()) {
				Element e = (Element) iter.next();
				String name = e.getAttribute("name");
				String value = (String) attrs.get(name);
				if (value != null) {
					map.put(name, value);
				}
			}
			// 计算表达式属性
			Map nmap = ExpressionGenerator.getInstance().generateValues(form, map,
					null, null);
			map.putAll(nmap);
			FormatFactory.format(form, map);
			// 给实体属性
			entity.attributes.putAll(map);
			entity.insert();
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
